<template>
  <a-row style="margin-top: 30px" justify="center"  class="article">
    <a-col  span="24" :md="{span : 22}" :xl="{span : 20}">
      <a-card title="文章编辑"  size="small">
        <template #extra>
          <a @click="router.go(-1)" href="#">返回</a>
        </template>
        <a-flex style="margin-bottom: 5px" wrap="wrap" :gap="10"  justify="flex-start" align="center">
          <a-space>
            <a-select
                v-if="article.problemId == '0'"
                v-model:value="article.typeId"
                style="width: 120px"
                :field-names="{ label: 'name', value: 'id', options: 'children' }"
                :options="typeList"
            >
              <template #suffixIcon><smile-outlined class="ant-select-suffix" /></template>
            </a-select>
          </a-space>
          <a-space>
            <a-select
                v-model:value="article.auth"
                style="width: 120px"
                :options="ARTICLE.auth"
            >
              <template #suffixIcon><smile-outlined class="ant-select-suffix" /></template>
            </a-select>
          </a-space>
          <a-upload
              v-model:file-list="fileList"
              name="avatar"
              list-type="picture"
              class="avatar-uploader"
              :max-count="1"
              :show-upload-list="false"
              :customRequest="upload"
              :before-upload="beforeUpload"
              @change="handleChange"
          >
            <a-button style="display: flex;align-items: center">
              上传封面
              <MonitorOutlined  @mouseenter="handlePreview" v-if="percent == 100" />
              <a-progress v-else  style="margin-left: 3px" type="circle" :percent="percent" :size="16" />
            </a-button>
          </a-upload>

          <a-input style="flex: 1;min-width: 120px"  v-model:value="article.articleTitle" placeholder="请输入标题"  />
          <a-button :loading="sending" @click="add"  type="primary">发布</a-button>
        </a-flex>
        <a-skeleton style="margin-top: 20px" active :loading="false" :rows="10">
          <md-editor style="margin-top: 10px" v-if="!loading" :defaultData="article.articleContent" ref="mdEditor"/>
        </a-skeleton>
      </a-card>
    </a-col>
  </a-row>
  <out-line/>
  <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="previewVisible = false">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>

<script lang="ts" setup>

import {qinUpload} from "@/utils/uploadUtils"
import MdEditor from "@/components/MdEditor/index.vue";
import {onMounted, reactive, ref} from "vue";
import {addArticle, getArticleById, updateArticle} from "@/api/article"
import {
  EyeOutlined,
  SmileOutlined,
  MonitorOutlined
} from '@ant-design/icons-vue';
import {listType} from "@/api/type";
import {message, UploadChangeParam, UploadProps} from "ant-design-vue";
import {ARTICLE} from "@/common/enum";
import router from "@/router";
const mdEditor = ref();
const loading = ref<boolean>(true)
const sending = ref<boolean>(false)
const article = reactive({
  id:"",
  typeId : "162",
  articleTitle: "",
  articleCover:"",
  articleContent:"",
  articleType:1,
  isComment:1,
  auth:1,
  seq:1,
  problemId:''
})
const typeList = ref()
const statusList = []
onMounted(() => {
  init();
})

const init = async () => {
  loading.value = true;
  const r = useRoute()
  const id =  r.query.articleId as string
  if(id != undefined && id != null){
    const res =  await getArticleById(id)
    Object.assign(article,res.data)
    if(article.articleCover)
      percent.value = 100
  }
  article.problemId  =  article.problemId ||  r.query.problemId as string || '0'
  const res = await listType({})
  typeList.value = res.data
  loading.value = false;
}

const add = () => {
  sending.value = true;
  article.articleContent = mdEditor.value.getValue()
  if(article.id == undefined || article.id == null || article.id == '')
    addArticle(article).then(() => {
      message.success("成功发布！");
      router.push("/discuss")
    }).finally(() => {
      sending.value = false;
    })
  else {
    updateArticle(article).then(() => {
      message.success("成功修改！");
      router.push("/discuss")
    }).finally(() => {
      sending.value = false;
    })
  }
}

const fileList = ref([]);
const handleChange = (info: UploadChangeParam) => {
  console.log(info)
};
const uploading = ref<boolean>(false)
const percent = ref(0)
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};
const upload = async (info) => {
  // console.log("upload")
  // console.log(info)
  uploading.value = true;
  try {
    const res = await qinUpload("articleCover/", info.file,(e) => {
      console.log(e)
      info.onProgress({percent : e.total.percent})
      percent.value = e.total.percent
    });
    article.articleCover = res as string
    message.success("上传成功")
    info.onSuccess()
  } catch (e) {
    info.onError(e)
  } finally {
    uploading.value = false;

  }
  // return new Promise( (resolve, reject) => {
  //   uploading.value = true;
  //   qinUpload("articleCover/",file).then(res=> {
  //     article.articleCover = res as string
  //     resolve();
  //   }).catch(err => {
  //     reject();
  //   }).finally(() => {
  //     uploading.value = false;
  //   })
  // })
}
const handlePreview =  () => {
  previewImage.value = article.articleCover;
  previewVisible.value = true;
};
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('预览');

</script>


<style lang="scss" scoped>

</style>
